# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
from django.contrib.contenttypes.models import ContentType
from django.core import serializers
from django.core.urlresolvers import reverse
from django.db import transaction
from django.db.models import Q, Count
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.template import loader, Context, RequestContext
from django.utils.encoding import StrAndUnicode, force_unicode, smart_unicode, smart_str
from settings import STATIC_ROOT, VERSION
from django.contrib.auth.models import User
import datetime, re

from models import *

def my_context(context):
	'''
	our context processor. Add to dict vars to send in ALL templates.
	'''
	entities=''
	if context.user.is_authenticated():
		entities=Entity.objects.all().filter(user=context.user,exist=True).order_by('-datetime')
	return {'VERSION': VERSION,'entities':entities}

@login_required
def index(request):
	entities=Entity.objects.all().filter(user=request.user,exist=True).order_by('-datetime')
	return render_to_response('main.html',RequestContext(request,{}))

@login_required
def to_index(request):
	return redirect(index)



@login_required
def add(request):
	is_link=False
	user=request.user
	line=request.POST['smart_input']
	link=re.findall('((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)',line)
	#return HttpResponse(link)
	if len(link) and line.startswith(link[0][0]):
		link=link[0][0]
		line=line.replace(link,'')
		is_link=True
	cat=re.findall('\&([^ ]*)',line)
	if len(cat):
		cat=cat[0]
		line=line.replace('&'+cat,'')
		try:
			cat=Category.objects.all().filter(title=cat).filter(Q(user=user)|Q(public=True))[0]
		except Exception,e:
			cat=''
	else:
		cat=''
		#return HttpResponse(cat)
	if is_link:
		alias=re.findall('\{([^ ]*)\}',line)
		if len(alias):
			alias=alias[0]
			line=line.replace('{'+alias+'}','')
		else:
			alias=''
		return link_add(request,user,link,line,cat,alias)
	else:
		pri=re.findall('\*([0-4]*)',line)
		if len(pri):
			pri=pri[0]
			line=line.replace('*'+pri,'')
		else:
			pri=0
		return stodo_add(request,user,line,pri,cat)


@login_required
def stodo_add(request,user,line,pri=0,cat=''):
	#return HttpResponse(cat.id)
	if cat:
		new_todo=SimpleTodo(title=line,user=user,priority=pri,category=cat)
	else:
		new_todo=SimpleTodo(title=line,user=user,priority=pri)
	new_todo.save()
	return render_to_response('entities/stodo.html',RequestContext(request,{'entity':new_todo}))


@login_required
def stodo_done(request,todo_id):
	todo=SimpleTodo.objects.get(pk=todo_id)
	if todo.done:
		todo.done=False
	else:
		todo.done=True
	todo.save()
	return HttpResponse('Success')


@login_required
def link_add(request,user,link,line,cat='',alias=''):
	#return HttpResponse(cat.id)
	if cat:
		new_link=Link(title=link,content=line,user=user,category=cat,alias=alias)
	else:
		new_link=Link(title=link,content=line,user=user,alias=alias)
	new_link.save()
	return render_to_response('entities/link.html',RequestContext(request,{'entity':new_link}))


@login_required
def entity_del(request,entity_id):
	entity=Entity.objects.get(pk=entity_id)
	entity.exist=False
	entity.del_datetime=datetime.datetime.now()
	entity.save()
	return HttpResponse('Success')

@login_required
def entity_remove(request,entity_id):
	entity=Entity.objects.get(pk=entity_id)
	entity.delete()
	#return HttpResponse('Success')
	return redirect(trash)

@login_required
def entity_restore(request,entity_id):
	entity=Entity.objects.get(pk=entity_id)
	entity.exist=True
	entity.del_datetime=''
	entity.save()
	#return HttpResponse('Success')
	return redirect(trash)

@login_required
def trash(request):
	trash=Entity.objects.all().filter(user=request.user,exist=False).order_by('-datetime')
	return render_to_response("trash.html",RequestContext(request,{'trash':trash}))

@login_required
def trash_clear(request):
	try:
		todel=Entity.objects.all().filter(user=request.user,exist=False)
		todel.delete()
	except:
		pass
	return redirect(trash)

@login_required
@transaction.commit_manually
def trash_done(request):
	todos=SimpleTodo.objects.all().filter(user=request.user,exist=True,done=True)
	for todo in todos:
		todo.exist=False
		todo.del_datetime=datetime.datetime.now()
		todo.save()
	transaction.commit()
	return redirect(trash)
@login_required
@transaction.commit_manually
def trash_restore(request):
	torst=Entity.objects.all().filter(user=request.user,exist=False)
	for entity in torst:
		entity.exist=True
		entity.del_datetime=''
		entity.save()
	transaction.commit()
	return redirect(trash)
